package com.example.data.factory.service.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.data.factory.common.Dto.DeletClassaifyDto;
import com.example.data.factory.common.Dto.InsertClassifyDto;
import com.example.data.factory.common.Dto.SearchClassifyDto;
import com.example.data.factory.common.common.StringConstant;
import com.example.data.factory.common.result.R;
import com.example.data.factory.common.util.CommonUtil;
import com.example.data.factory.entity.entity.Classify;
import com.example.data.factory.mapper.mapper.ClassifyMapper;
import com.example.data.factory.service.service.ClassifyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lhy
 * @since 2025-03-03
 */
@Service
public class ClassifyServiceImpl extends ServiceImpl<ClassifyMapper, Classify> implements ClassifyService {
    @Resource
    private ClassifyMapper classifyMapper;
    @Resource
    private CommonUtil commonUtil;

    @Override
    public R<Classify> inserts(InsertClassifyDto insertClassifyDto, HttpServletRequest request) {
        // 如果是顶级分类（parent_id == 0），不需要检查父级分类
        if (insertClassifyDto.getParentId () == 0) {
            Classify classify = new Classify ();
            classify.setName ( insertClassifyDto.getName () );
            classify.setLevel ( 1 ); // 顶级分类层级为1
            classify.setParentId ( 0 );
            classify.setType ( insertClassifyDto.getType () );
            classify.setCreateTime ( LocalDateTime.now () );
            classify.setUpdateTime ( LocalDateTime.now () );

            this.save ( classify );
            return R.Success ( "顶级分类添加成功" );
        } else {
            // 查询父级分类，同时过滤掉已删除的分类
            LambdaQueryWrapper<Classify> queryWrapper = new LambdaQueryWrapper<> ();
            queryWrapper.eq ( Classify::getId, insertClassifyDto.getParentId () )
                    .eq ( Classify::getDeleted, 0 ); // 确保只查询未删除的分类

            // 尝试获取父级分类列表
            List<Classify> parentCategories = this.list ( queryWrapper );

            if (parentCategories.isEmpty ()) {
                return R.Failed ( "指定的父级分类不存在或已被删除" );
            }

            // 创建新的分类对象
            Classify classify = new Classify ();
            Integer level = parentCategories.get ( 0 ).getLevel () + 1; // 使用第一个找到的父级分类来计算层级

            // 设置新分类的各项属性
            classify.setName ( insertClassifyDto.getName () );
            classify.setLevel ( level );
            classify.setParentId ( insertClassifyDto.getParentId () );
            classify.setType ( insertClassifyDto.getType () );
            String username = commonUtil.extractUsernameFromRequest ( request );
            classify.setCreateBy ( username );
            classify.setCreateTime ( LocalDateTime.now () );
            classify.setUpdateTime ( LocalDateTime.now () );

            // 保存新分类到数据库
            this.save ( classify );

            return R.Success ( "分类添加成功" );
        }
    }

    @Override
    public R<Classify> delete(DeletClassaifyDto deletClassaifyDto) {
        // 查询当前分类
        Classify one = this.getOne ( new LambdaQueryWrapper<Classify> ().eq ( Classify::getId, deletClassaifyDto.getId () ) );
        if (one == null) {
            return R.Failed ( "未找到指定的分类" );
        }

        // 判断是否为顶级目录，如果是则删除其子目录
        if (one.getParentId () == 0) {
            // 批量更新子目录为已删除
            this.update ( new LambdaUpdateWrapper<Classify> ()
                    .eq ( Classify::getParentId, one.getId () )
                    .set ( Classify::getDeleted, (byte) 1 ) );
        }

        // 标记当前分类为已删除
        one.setDeleted ( (byte) 1 );
        boolean save = this.updateById ( one );

        // 返回结果
        if (save) {
            return R.Success ( StringConstant.UPDATESUCCESS );
        }
        return R.Failed ( StringConstant.UPDATEFAILED );

    }

//    @Override
//    public R<Classify> searchs(SearchClassifyByTypeDto searchClassifyByTypeDto) {
//      try {  List<Classify> deleted = classifyMapper.selectList ( new QueryWrapper<Classify> ().eq ( "deleted", false ) );
//        Map<Integer,Classify> map = deleted.stream().collect ( Collectors.toMap ( Classify::getId,item->item ) );
//        QueryWrapper<Classify> queryWrapper = new QueryWrapper<> ();
//        queryWrapper.eq ( "deleted",false );
//        //根据分类查询分类
//        if (searchClassifyByTypeDto.getType () != null && !searchClassifyByTypeDto.getType ().trim ().isEmpty ()) {
//            queryWrapper.like ( "type",searchClassifyByTypeDto.getType () );
//        }
//      List<Classify> classifies = classifyMapper.selectList ( queryWrapper );
//        if (classifies.isEmpty ()) {
//            return R.Failed ("没有找到数据");
//        }
//        Set<Integer> set = new HashSet<> ();
//        List<Classify> result = new ArrayList<> ();
//        for (Classify classify : classifies) {
//            Classify fullHierarchy = buildFullHierarchy ( classify,map,set );
//            if (!set.contains(classify.getId())) { // 避免重复添加
//                result.add(fullHierarchy);
//                set.add(classify.getId());
//            }
//        }
//        return R.Success(result);
//    } catch (Exception e) {
//        e.printStackTrace();
//        return R.Failed("系统异常：" + e.getMessage());
//    }
//    }

    @Override
    public R<List<Classify>> search(SearchClassifyDto searchClassifyDto) {
        try {
            // 获取所有未删除的分类并构建Map
            List<Classify> allClassifies = classifyMapper.selectList ( new QueryWrapper<Classify> ().eq ( "deleted", 0 ) );
            Map<Integer, Classify> map = allClassifies.stream ()
                    .collect ( Collectors.toMap ( Classify::getId, item -> item ) );

            // 构建初始查询条件
            QueryWrapper<Classify> queryWrapper = new QueryWrapper<> ();
            queryWrapper.eq ( "deleted", 0 );

            // 根据名称查找初始分类
            if (searchClassifyDto.getName () != null && !searchClassifyDto.getName ().trim ().isEmpty ()) {
                queryWrapper.like ( "name", searchClassifyDto.getName () );
            }

            // 增加 type 条件过滤
            if (searchClassifyDto.getType () != null && !searchClassifyDto.getType ().trim ().isEmpty ()) {
                queryWrapper.eq ( "type", searchClassifyDto.getType () );
            }

            List<Classify> initialClassifies = classifyMapper.selectList ( queryWrapper );
            if (initialClassifies.isEmpty ()) {
                return R.Failed ( "未找到与条件匹配的分类" );
            }

            // 查找并构建完整的层次结构
            Set<Integer> processedIds = new HashSet<> (); // 用于记录已处理的节点ID
            List<Classify> result = new ArrayList<> ();
            for (Classify initialClassify : initialClassifies) {
                Classify fullHierarchy = buildFullHierarchy ( initialClassify, map, processedIds );
                if (!processedIds.contains ( initialClassify.getId () )) { // 避免重复添加
                    result.add ( fullHierarchy );
                    processedIds.add ( initialClassify.getId () );
                }
            }

            return R.Success ( result );
        } catch (Exception e) {
            e.printStackTrace ();
            return R.Failed ( "系统异常：" + e.getMessage () );
        }
    }

    private Classify buildFullHierarchy(Classify classify, Map<Integer, Classify> allClassifies, Set<Integer> processedIds) {
        // 查找并添加所有子级
        addChildren ( classify, allClassifies, processedIds );

        // 查找并设置父级
        setParent ( classify, allClassifies, processedIds );

        return classify;
    }

    private Classify addChildren(Classify parent, Map<Integer, Classify> allClassifies, Set<Integer> processedIds) {
        for (Classify item : allClassifies.values ()) {
            if (item.getParentId () != null && item.getParentId ().equals ( parent.getId () )) {
                if (processedIds.contains ( item.getId () )) {
                    continue; // 跳过已处理的节点
                }

                if (parent.getChildren () == null) {
                    parent.setChildren ( new ArrayList<> () );
                }

                // 创建子节点的副本并递归添加子级
                Classify childWithChildren = new Classify ();
                childWithChildren.setId ( item.getId () );
                childWithChildren.setName ( item.getName () );
                childWithChildren.setLevel ( item.getLevel () );
                childWithChildren.setParentId ( item.getParentId () );
                childWithChildren.setType ( item.getType () );
                childWithChildren.setDeleted ( item.getDeleted () );
                childWithChildren.setCreateTime ( item.getCreateTime () );
                childWithChildren.setUpdateTime ( item.getUpdateTime () );

                // 标记为已处理
                processedIds.add ( item.getId () );

                // 递归添加子级
                addChildren ( childWithChildren, allClassifies, processedIds );

                // 将子节点添加到父节点的子列表中
                parent.getChildren ().add ( childWithChildren );
            }
        }
        return parent;
    }

    private void setParent(Classify child, Map<Integer, Classify> allClassifies, Set<Integer> processedIds) {
        Integer parentId = child.getParentId ();
        while (parentId != null && parentId != 0 && allClassifies.containsKey ( parentId )) {
            Classify parent = allClassifies.get ( parentId );

            if (processedIds.contains ( child.getId () )) {
                break; // 跳过已处理的节点
            }

            if (parent.getChildren () == null) {
                parent.setChildren ( new ArrayList<> () );
            }

            // 避免重复添加
            Classify finalChild = child;
            boolean isDuplicate = parent.getChildren ().stream ()
                    .anyMatch ( existingChild -> existingChild.getId ().equals ( finalChild.getId () ) );

            if (!isDuplicate) {
                parent.getChildren ().add ( child );
            }

            // 继续向上查找父级
            child = parent;
            parentId = child.getParentId ();
        }
    }
}
